import { _decorator, Asset, AssetManager, assetManager } from 'cc';
const { ccclass } = _decorator;

@ccclass('ResManager')
export class ResManager {
    public static async load<T extends Asset>(bundleName: string, path: string, type: _typeAsset<T>) {
        let bundle = await this.getBundle(bundleName);
        return await this.getAsset(bundle, path, type);
    }

    private static getBundle(bundleName: string) {
        return new Promise<AssetManager.Bundle>((resolve, reject) => {
            let bundle = assetManager.getBundle(bundleName);
            if (bundle) {
                resolve(bundle);
            } else {
                assetManager.loadBundle(bundleName, (err, bundle) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(bundle);
                    }
                });
            }
        });
    }

    private static getAsset<T extends Asset>(bundle: AssetManager.Bundle, path: string, type: _typeAsset<T>) {
        return new Promise<T>((resolve, reject) => {
            let asset = bundle.get(path, type);
            if (asset) {
                resolve(asset);
            } else {
                bundle.load(path, type, (err, asset) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(asset);
                    }
                });
            }
        });
    }
}


type _typeAsset<T = unknown> = new (...args: any[]) => T;